package com.netty.pool;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import com.netty.handler.DefaultChannelPoolHandler;

import io.netty.channel.pool.AbstractChannelPoolHandler;
import io.netty.channel.pool.ChannelPool;
/**
 * channelpool工厂
 * @author hmm
 *
 */
public class NettyClientPoolFactory{

	private final int maxConnections = 2;
	private final int maxInitSize = 2;
	private final DefaultChannelPoolMap poolMap;
	private final Map<String, InetSocketAddress> inetMap = new HashMap<String, InetSocketAddress>();
	
	/**
	 * 多地址初始化连接池
	 */
	public NettyClientPoolFactory(){
		poolMap = new DefaultChannelPoolMap(maxConnections, maxInitSize);
		initPool("locahost", "127.0.0.1", 8080);
	}
	
	private void initPool(String poolName, String host, int port){
		InetSocketAddress inet = new InetSocketAddress(host, port);
		this.setPool(poolName, inet, new DefaultChannelPoolHandler(false, true, false));
	}
	
	private void setPool(String name, InetSocketAddress inet, AbstractChannelPoolHandler channelPoolHandler){
		if(null != channelPoolHandler){
			poolMap.addHandler(inet, channelPoolHandler);
		}
		poolMap.get(inet);
		inetMap.put(name, inet);
	}
	
	public ChannelPool getPool(String source){
		InetSocketAddress inet = inetMap.get(source);
		if(null == inet){
			return null;
		}
		return poolMap.get(inet);
	}
	
	public void close(){
		System.out.println("准备关闭连接池");
		poolMap.shutdown();
		poolMap.close();
	}
}
